﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using API;
using CoreGraphics;
using CoreText;
using Foundation;
using mb;
using mb.iOS;
using Masonry;
using MyExtensions;
using ObjCRuntime;
using UIKit;

// using PagerViewManager = PagerManager.PagerViewManager;

namespace libmp
{
    public class VCHome : UIViewController
    {
        static ILog logger = mb.ServiceLocator.Instance.Get<ILog>();

        PagerViewManager pagerViewManager;
        UIView titleBar;

        public VCHome()
        {
            TabBarItem = new UITabBarItem("首页", null, 0);
        }

        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);
            pagerViewManager?.UpdateFrames(() => { }, false);
            // logger.Log("--VCHome ViewDidAppear---");
        }
        public override void ViewDidLayoutSubviews()
        {
            pagerViewManager?.UpdateFrames(() => { }, false);
            // logger.Log("VCHome ViewDidLayoutSubviews", View.Frame);
        }

        public override void ViewDidLoad()
        {
            // logger.Log("--VCHome ViewDidLoad---");
            var bkView = new UIView() { BackgroundColor = Util.MainBKColor };
            bkView.SetParent(View).MakeConstraints(m =>
            {
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Left.Right.Bottom.EqualTo(View);
            });

            titleBar = new UIView()
            {
                BackgroundColor = Util.MainColor,
            };
            titleBar.SetParent(View);
            titleBar.MakeConstraints(m =>
            {
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Left.EqualTo(View);
                m.Right.EqualTo(View);
                m.Height.EqualTo(NSObject.FromObject(48));
            });

            //圆形头像
            UIImageView avatarImage = new UIImageView();
            avatarImage.Frame = new CoreGraphics.CGRect(0, 0, 24, 24);
            avatarImage.Image = UIImage.FromFile($"{App.HotStorageRoot}/res/user/avatar.png");
            avatarImage.Layer.CornerRadius = avatarImage.Frame.Size.Width / 2;
            avatarImage.Layer.MasksToBounds = true;
            avatarImage.SetParent(titleBar);
            avatarImage.UserInteractionEnabled = true;
            avatarImage.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(titleBar.CenterY());
                m.Left.EqualTo(NSObject.FromObject(10));
                m.Width.EqualTo(NSObject.FromObject(24));
                m.Height.EqualTo(NSObject.FromObject(24));
            });
            var tbtn = new UIButton() { };
            tbtn.SetParent(avatarImage);
            tbtn.MakeConstraints(m => { m.Edges.EqualTo(avatarImage); });
            tbtn.TouchUpInside += async(s, e) =>
            {
                bool r = await MyPopupManager.ShowYesNo("是否退出", new string[] { "取消", "确定" }, (sel) =>
                {
                    logger.Log("on sel", sel);
                });
                logger.Log("select", r);
                if (r)
                {
                    // System.Environment.Exit(0);
                    // await MyPopupManager.ShowMsgBox("马上就秒退了", "不行啊");
                    UIApplication.SharedApplication.PerformSelector(new ObjCRuntime.Selector("terminateWithSuccess"), null, 0f);
                }
            };

            //构建搜索框
            float Width = (float) View.Frame.Size.Width - 60;
            string placeholder = "输入关键字查找";
            var textUIcolor = UIColor.White;
            var backgroundColor = UIColor.FromRGB(211, 97, 130);
            var clearImg = UIImage.FromFile($"{App.HotStorageRoot}/res/search/Close_01.png");
            var leftAskImg = UIImage.FromFile($"{App.HotStorageRoot}/res/search/ask.png");
            var textFont = UIFont.SystemFontOfSize(14);
            UISearchBar searchBar = Util.createMySearchBar(Width, placeholder, textUIcolor, clearImg, leftAskImg, textFont, backgroundColor);
            searchBar.Frame = new RectangleF(50, 10, Width, 28);
            searchBar.Layer.CornerRadius = 13;
            searchBar.Layer.MasksToBounds = true;
            searchBar.SetParent(titleBar);
            //UISearchBar searchBar = createMySearchBar(titleBar);
            //搜索事件
            searchBar.SearchButtonClicked += (s, e) =>
            {
                logger.Log("search click", searchBar.Text);
                searchBar.EndEditing(true);
            };

            searchBar.OnEditingStarted += (s, e) =>
            {
                logger.Log("editing start");
                UITapGestureRecognizer tap = null;
                tap = new UITapGestureRecognizer(() =>
                {
                    logger.Log("editing end by clickout");
                    View.EndEditing(true);
                    View.RemoveGestureRecognizer(tap);
                });
                tap.CancelsTouchesInView = true;
                View.AddGestureRecognizer(tap);
            };

            LoadHomeMovieView();
        }

        void LoadHomeMovieView()
        {
            var vch = new VCHomeMovie();
            AddChildViewController(vch);
            vch.View.SetParent(View);
            vch.View.MakeConstraints(m =>
            {
                m.Left.Right.EqualTo(View);
                m.Top.EqualTo(titleBar.Bottom());
                m.Bottom.EqualTo(this.BottomLayoutGuideTop());
            });
        }

        void LoadPageView()
        {

            var vButtons = new UIView() { BackgroundColor = UIColor.FromRGB(200, 200, 200), };
            vButtons.SetParent(View);
            vButtons.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Top.EqualTo(titleBar.Bottom());
                m.Right.EqualTo(View);
                m.Height.EqualTo(NSObject.FromObject(50));
            });
            var vPages = new UIView();
            vPages.SetParent(View);
            vPages.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Top.EqualTo(vButtons.Bottom());
                m.Right.EqualTo(View);
                m.Bottom.EqualTo(this.BottomLayoutGuideTop());
            });

            pagerViewManager = new PagerViewManager(this, vPages, true);
            pagerViewManager.SetButtonsContainer(vButtons);
            // pagerViewManager.EnableSwipe = false;
            // logger.Log("pageview gesture", mb.iOS.Util.AddrOfObject(pagerViewManager._panGestureRecognizer));

            // var titles = new string[] { "视频", "有声", "小说", "游戏", "搞笑", "咖啡", "吃饭" };
            var titles = new string[] { "视频", "有声", "小说" };
            UIViewController[] vcs = new []
            {
                new VCHomeMovie() { ParentPanGR = pagerViewManager._panGestureRecognizer },
                new UIViewController(),
                new UIViewController(),
            };
            for (int i = 0; i < titles.Length; i++)
            {
                var idx = i; //bind upvalue
                var vc = vcs[i];
                var btn = new UIButton(new CGRect(0, 0, 60f, vButtons.Frame.Height));
                btn.SetTitleColor(Util.MainColor, UIControlState.Selected);
                btn.SetTitleColor(UIColor.Gray, UIControlState.Normal);
                btn.SetTitle(titles[i], UIControlState.Normal);
                btn.TouchUpInside += delegate { pagerViewManager.SetCurrentPage(idx); };
                pagerViewManager.AddPageViewController(vc, btn);
                if (i > 0)
                    vc.View.BackgroundColor = UIColor.FromRGB(255 - 80 * i, 100, 80 * i);
            }

            pagerViewManager.SetCurrentPage(0, false);
        }

    }
}